/**
 * 
 */
package com.elifes.hsj.client.netty;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;
import org.jboss.netty.channel.MessageEvent;

import com.elifes.hsj.client.HSJClient;
import com.elifes.hsj.client.netty.task.BaseTask;
import com.elifes.hsj.client.netty.task.FindTask;
import com.elifes.hsj.client.netty.task.ITask;
import com.elifes.hsj.client.netty.task.InsertTask;
import com.elifes.hsj.packet.IPacket;
import com.elifes.hsj.packet.PacketEnum;

/**
 * 
 * 描述：对hs返回结果进行处理
 * @author yangqiang
 * 
 */
public class TaskManager {
	private static final Logger logger = Logger.getLogger(TaskManager.class);
	private static TaskManager self = new TaskManager();
	private Executor executor = Executors.newFixedThreadPool(80);

	private Map<PacketEnum, ITask> taskMap = new HashMap<PacketEnum, ITask>();

	public TaskManager() {
		BaseTask baseTask = new BaseTask();
		taskMap.put(PacketEnum.AUTH, baseTask);
		taskMap.put(PacketEnum.OPEN_INDEX, baseTask);
		taskMap.put(PacketEnum.INSERT, new InsertTask());
		taskMap.put(PacketEnum.FIND, new FindTask());
		taskMap.put(PacketEnum.MOD, new FindTask());
		//taskMap.put(PacketEnum.AUTH, baseTask);
	}

	public static TaskManager getInstance() {
		return self;
	}

	/**
	 * 描述：hs返回后再回收连接
	 * @param event
	 * @param hsjClient
	 */
	public void execute(final MessageEvent event, final HSJClient hsjClient) {
		Runnable processor = new Runnable() {
			public void run() {
				String responseMsg = (String) event.getMessage();
				IPacket curPacket = (IPacket) hsjClient.getPendingRequest()
						.get(event.getChannel().getId());	
				
				hsjClient.removePendingRequest(event.getChannel().getId());
				hsjClient.addChannelPool(curPacket.getIndexId(), event.getChannel());
				
				ITask task = taskMap.get(curPacket.getType());
				if (task == null) {
					logger.info(curPacket.getType() + "no task!");
					return;
				}
				task.handleResponse(responseMsg, curPacket);
			}
		};
		executor.execute(processor);
	}
	
	/**
	 * 描述：hs返回后根据请求队列处理
	 * @param event
	 * @param curPacket
	 */
	public void execute(final MessageEvent event, final IPacket curPacket) {
		Runnable processor = new Runnable() {
			public void run() {
				String responseMsg = (String) event.getMessage();
				ITask task = taskMap.get(curPacket.getType());
				if (task == null) {
					logger.info(curPacket.getType() + "no task!");
					return;
				}
				task.handleResponse(responseMsg, curPacket);
			}
		};
		executor.execute(processor);
	}
}
